package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.otw.common.OtwConstant;
import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.otw.dto.DeliveryOrderCreateCallbackDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap.dto.DeliveryOrderSapDTORequest;
import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap.dto.DeliveryOrderSapDetailDTORequest;
import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.MnSAPStatus;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpTokenUtil;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpUtils;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.RemoveZeroUtil;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.util.IntegrateUtils;
import com.alibaba.citrus.ots.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.citrus.ots.common.util.TimeUtil;
import com.alibaba.cloud.retail.wms.api.constants.WmsOrderMainTypeEnum;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crunifiedinventory.api.allocateorderwrite.service.AllocateOrderWriteService;
import com.epoch.app.crunifiedinventory.api.consignmentorderwrite.service.ConsignmentOrderWriteService;
import com.epoch.app.crunifiedinventory.consignmentorderquery.service.ConsignmentOrderQueryService;
import com.epoch.app.crunifiedinventory.dto.request.ConsignmentOrderUpdateRequest;
import com.epoch.app.crunifiedinventory.dto.request.ConsignmentOrderWriteCreateRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderDeliveryResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderDeliveryRequest;
import com.epoch.app.crunifiedinventory.model.dto.ConsignmentOrderLineRequest;
import com.epoch.app.crunifiedinventory.model.dto.ConsignmentOrderLineUpdateReq;
import com.epoch.app.crunifiedinventory.model.dto.ConsignmentOrderQueryRequest;
import com.epoch.app.crunifiedinventory.sdo.ConsignmentOrderSearchResponse;
import com.epoch.app.otsapplicationadaptersdk.contants.OtsApplicationAdapterSdkConstants;
import com.epoch.app.otsapplicationadaptersdk.mnsapif033v2.service.MnSapIf033V2Service;
import com.epoch.app.otsapplicationadaptersdk.model.dto.*;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommResponse;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommSDO;
import com.epoch.app.otsapplicationadaptersdk.service.OtsApplicationAdapterSdkService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SAP交货单明细回传中台（创建、修改）（F-B）
 * sap -> 中台
 * @author baizhuo
 * @version 1.0
 * @date 2023/12/28 21:07
 */
@Component
@Primary
public class MnSapIf033V2ServiceImpl implements MnSapIf033V2Service {

    private final Log log = Log.getLogger(MnSapIf033V2ServiceImpl.class);

    @Resource
    private ConsignmentOrderWriteService consignmentOrderWriteService;

    @Resource
    private ConsignmentOrderQueryService consignmentOrderQueryService;

    @Resource
    private OtsApplicationAdapterSdkService otsApplicationAdapterSdkService;

    @Resource
    private AllocateOrderWriteService allocateOrderWriteService;

    @Autowired
    private HttpUtils httpUtils;

    @Override
    @ProcessInvoker(remark = "MnSapIf033V2Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public MnSapCommResponse deliveryOrderFBDetailFeedback(MnSapIf033Request mnSapIf033Request) {
        log.info("MnSapIf033V2Service deliveryOrderFBDetailFeedback param:{}", JSON.toJSONString(mnSapIf033Request));
        MnSapCommResponse mnSapCommResponse = new MnSapCommResponse();
        try {
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            //if (mnSapIf033Request == null) {
            //    mnSapIf033Request = IntegrateUtils.safeGetMessageObject(MnSapIf033Request.class);
            //}
            //mnSapIf033Request.setDeliverOrderNo(RemoveZeroUtil.removeZeroPrefix(mnSapIf033Request.getDeliverOrderNo()));
            //mnSapCommResponse.setMessageId(mnSapIf033Request.getMessageHeader().getMESSAGEID());
            //mnSapCommResponse.setInterfacePath(mnSapIf033Request.getMessageHeader().getINTERFACE());
            ////先根据sap交货单号查询是否已有中台交货单，如果有中台交货单，则调update接口，如果没有中台交货单，则调create接口
            //ConsignmentOrderQueryRequest consignmentOrderQueryRequest = new ConsignmentOrderQueryRequest();
            //consignmentOrderQueryRequest.setOuterDeliveryOrderId(RemoveZeroUtil.removeZeroPrefix(mnSapIf033Request.getDeliverOrderNo()));
            //log.info("mnSapIf033 searchOrder consignmentOrder param:{}", JSON.toJSONString(consignmentOrderQueryRequest));
            //Result<ConsignmentOrderSearchResponse> queryConsignmentOrderResult = consignmentOrderQueryService.searchOrder(consignmentOrderQueryRequest);
            //log.info("mnSapIf033 searchOrder consignmentOrder result:{}", JSON.toJSONString(queryConsignmentOrderResult));
            //if (!queryConsignmentOrderResult.isSuccess()) {
            //    log.error("consignmentOrderQueryService searchOrder not find");
            //    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
            //    mnSapCommSDO.setMessage(MnSAPStatus.ERROR.getMsg());
            //    return mnSapCommResponse;
            //}
            //Result<Void> saveOrUpdateConsignmentOrderResult=null;
            //if (null == queryConsignmentOrderResult.getResult()) {
            //    // todo wxy  033接口作为017接口的数据补充，017都执行，033只走update，把033这块逻辑移到bc_link，方便重试（017还未创建交货单的话）
            //    //创建中台交货单
            //    //ConsignmentOrderWriteCreateRequest consignmentOrderWriteCreateRequest = convertConsignmentOrderWriteCreateRequest(mnSapIf033Request);
            //    //log.info("mnSapIf033 createOrder consignmentOrder param:{}", JSON.toJSONString(consignmentOrderWriteCreateRequest));
            //    //saveOrUpdateConsignmentOrderResult = consignmentOrderWriteService.createOrder(consignmentOrderWriteCreateRequest);
            //    //log.info("mnSapIf033 createOrder consignmentOrder result:{}", JSON.toJSONString(saveOrUpdateConsignmentOrderResult));
            //
            //
            //
            //    ////todo bz 将中台交货单号（实际是sap交货单号）保存到中台出入库单上
            //    ////中台交货单没有自己的交货单号，用sap的交货单号. 交货单号要去除前缀0
            //    //WarehousingOrderDTO  updateWarehousingOrderDTO = new WarehousingOrderDTO();
            //    //String updateDeliverOrderNo =RemoveZeroUtil.removeZeroPrefix(mnSapIf033Request.getDeliverOrderNo());
            //    //updateWarehousingOrderDTO.setPrevWmsOrderId(updateDeliverOrderNo);
            //    //updateWarehousingOrderDTO.setDeliveryOrderId(updateDeliverOrderNo);
            //    //Result<WarehousingOrderDTO> warehousingOrderDTOResult = queryInOutboundBySaleOrderId(mnSapIf033Request.getOrderNo());
            //    //if(null !=warehousingOrderDTOResult.getResult()){
            //    //    updateWarehousingOrderDTO.setWarehousingOrderId(warehousingOrderDTOResult.getResult().getWarehousingOrderId());
            //    //    List<WmsOrderDetailDTO> wmsOrderDetailList = mnSapIf033Request.getGoodsInfos().stream().map(mnSapIf033Detail -> {
            //    //        WmsOrderDetailDTO wmsOrderDetailDTO = new WmsOrderDetailDTO();
            //    //        wmsOrderDetailDTO.setDeliverySubOrderId(SapAndCrmFieldDealUtils.generateIdField(mnSapIf033Detail.getProjectNo()));
            //    //        wmsOrderDetailDTO.setWmsOrderDetailId("");
            //    //        return wmsOrderDetailDTO;
            //    //    }).collect(Collectors.toList());
            //    //    updateWarehousingOrderDTO.setWmsOrderDetailList(wmsOrderDetailList);
            //    //    log.info("mnSapIf033 updateWmsOrderInner request:{}", JSON.toJSONString(updateWarehousingOrderDTO));
            //    //    Result<Void> updateResult = otsApplicationAdapterSdkService.updateWmsOrderInner(updateWarehousingOrderDTO);
            //    //    log.info("mnSapIf033 updateWmsOrderInner result:{}", JSON.toJSONString(updateResult));
            //    //    if(!updateResult.isSuccess()){
            //    //        mnSapCommSDO.setStatus(updateResult.getErrorCode());
            //    //        mnSapCommSDO.setMessage("033交货单更新到出入库失败: "+updateResult.getMessage());
            //    //    }
            //    //}else{
            //    //    log.info("mnSapIf033 根据订单查询出入库单失败或为空 param:{}", JSON.toJSONString(warehousingOrderDTOResult));
            //    //}
            //    //根据sap交货单号查询中台出入库单
            //} else {
            //    ConsignmentOrderUpdateRequest consignmentOrderUpdateRequest = convertConsignmentOrderUpdateRequest(mnSapIf033Request);
            //    log.info("mnSapIf033 update consignmentOrder param:{}", JSON.toJSONString(consignmentOrderUpdateRequest));
            //    saveOrUpdateConsignmentOrderResult = consignmentOrderWriteService.update(consignmentOrderUpdateRequest);
            //    log.info("mnSapIf033 update consignmentOrder result:{}", JSON.toJSONString(saveOrUpdateConsignmentOrderResult));
            //}
            //
            //try {
            //    AllocateOrderDeliveryRequest allocateOrderDeliveryRequest = new AllocateOrderDeliveryRequest();
            //    allocateOrderDeliveryRequest.setOutAllocateOrderId(mnSapIf033Request.getOrderNo());
            //    allocateOrderDeliveryRequest.setDeliveryDate(mnSapIf033Request.getProofDate());
            //    log.info("MnSapIf033V2ServiceImpl#delivered request={}", JSON.toJSONString(allocateOrderDeliveryRequest));
            //    Result<AllocateOrderDeliveryResponse> result = allocateOrderWriteService.delivered(allocateOrderDeliveryRequest);
            //    log.info("MnSapIf033V2ServiceImpl#delivered result={}", JSON.toJSONString(result));
            //} catch (Exception e) {
            //    log.error("MnSapIf033V2ServiceImpl#delivered error", e);
            //}
            //
            //if (null != saveOrUpdateConsignmentOrderResult && saveOrUpdateConsignmentOrderResult.isSuccess()) {
            //    mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
            //    mnSapCommSDO.setMessage(MnSAPStatus.SUCCESS.getMsg());
            //    // todo wxy 判断是否需要同步OTW
            //    // 经过梳理，需要同步OTW的场景为：出库单+（F-B-b中的F-B||F1-B分仓||调拨单+发货仓为试点内）
            //    bcLink009Request( mnSapIf033Request);
            //
            //} else {
            Map<String, String> header = HttpTokenUtil.generateHttpHeader();
            String urlPrefix = OtsApplicationAdapterSdkConstants.urlPrefix();
            String url = urlPrefix + "api/mn_bc_link/inOutBoundOrderDetailSyncOtw033";
            log.info("MnSapIf033V2ServiceImpl#inOutBoundOrderDetailSyncOtw033,url:{}, header:{}, param:{}", url, header, JSON.toJSONString(mnSapIf033Request));
            ResponseEntity<com.alibaba.cirtus.ots.application.adapter.ability.model.Result> post = httpUtils.post(url, header, mnSapIf033Request, com.alibaba.cirtus.ots.application.adapter.ability.model.Result.class);
            com.alibaba.cirtus.ots.application.adapter.ability.model.Result result = post.getBody();
            log.info("MnSapIf033V2ServiceImpl#inOutBoundOrderDetailSyncOtw033 result:{}", JSON.toJSONString(result));
            if (result.isSuccess()) {
                mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                mnSapCommSDO.setMessage(MnSAPStatus.SUCCESS.getMsg());
            }else {
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage(MnSAPStatus.ERROR.getMsg());
            }
            //}
            mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
        } catch (Exception e) {
            log.error("deliveryOrderFBDetailFeedback error", e);
            throw e;
        }
        return mnSapCommResponse;
    }

    private ConsignmentOrderUpdateRequest convertConsignmentOrderUpdateRequest(MnSapIf033Request mnSapIf033Request) {
        //当前ConsignmentOrderUpdateRequest与ConsignmentOrderWriteCreateRequest相同，convert方法可以复用
        ConsignmentOrderUpdateRequest consignmentOrderUpdateRequest = new ConsignmentOrderUpdateRequest();
        consignmentOrderUpdateRequest.setOuterDeliveryOrderId(mnSapIf033Request.getDeliverOrderNo());
        consignmentOrderUpdateRequest.setPickingStatus(mnSapIf033Request.getPickingStatus());
        //todo bz,sap 交货单明细回传会返回过账状态，但这个时间应该还没有过账，是否不用保存？待与pd确认
//        consignmentOrderWriteCreateRequest.set(mnSapIf033Request.getBillStatus());
        consignmentOrderUpdateRequest.setDeliverType(mnSapIf033Request.getDeliverType());
        //todo bz,与pd确认sap返回的orderNo是否是sap的销售单号
        consignmentOrderUpdateRequest.setOuterSalesOrderId(mnSapIf033Request.getOrderNo());
        //todo bz,凭证日期怎么传
//        consignmentOrderWriteCreateRequest.set(mnSapIf033Request.getProofDate());
//        consignmentOrderWriteCreateRequest.set(mnSapIf033Request.getFactoryCode());
        //todo bz,工厂编码及库存地点
//        consignmentOrderWriteCreateRequest.set(mnSapIf033Request.getWareHouseCode());
        consignmentOrderUpdateRequest.setTransportSite(mnSapIf033Request.getTransportSite());
        consignmentOrderUpdateRequest.setTransportRouteCode(mnSapIf033Request.getTransportRouteCode());
        consignmentOrderUpdateRequest.setTransportRouteDesc(mnSapIf033Request.getTransportRouteDesc());
        consignmentOrderUpdateRequest.setNetWeight(mnSapIf033Request.getNetWeight());
        consignmentOrderUpdateRequest.setGrossWeight(mnSapIf033Request.getGrossWeight());
        consignmentOrderUpdateRequest.setVolume(mnSapIf033Request.getVolume());
        consignmentOrderUpdateRequest.setWeightUnit(mnSapIf033Request.getWeightUnit());
        consignmentOrderUpdateRequest.setVolumeUnit(mnSapIf033Request.getVolumeUnit());
        consignmentOrderUpdateRequest.setTransportRequire(mnSapIf033Request.getTransportRequire());
        consignmentOrderUpdateRequest.setSendToCode(mnSapIf033Request.getSendtoCode());
        consignmentOrderUpdateRequest.setSoldToCode(mnSapIf033Request.getSoldToCode());
        consignmentOrderUpdateRequest.setSalesOrgId(mnSapIf033Request.getSaleOrg());
        consignmentOrderUpdateRequest.setDistributeChannel(mnSapIf033Request.getDistributeChannel());
        consignmentOrderUpdateRequest.setDepartment(mnSapIf033Request.getDepartment());
        consignmentOrderUpdateRequest.setDeliverPriority(mnSapIf033Request.getDeliverPriority());
        consignmentOrderUpdateRequest.setDeliverPlanDate(mnSapIf033Request.getDeliverPlanDate());
        consignmentOrderUpdateRequest.setSendPlanDate(mnSapIf033Request.getSendPlanDate());
        consignmentOrderUpdateRequest.setRemark(mnSapIf033Request.getRemark());
        consignmentOrderUpdateRequest.setCreator(mnSapIf033Request.getCreateCode());
        consignmentOrderUpdateRequest.setCreatDate(TimeUtil.parseSimpleDateFormat(mnSapIf033Request.getCreateDate()));
        consignmentOrderUpdateRequest.setModifier(mnSapIf033Request.getUpdateCode());
        consignmentOrderUpdateRequest.setModifidDate(TimeUtil.parseSimpleDateFormat(mnSapIf033Request.getUpdateDate()));
        List<ConsignmentOrderLineUpdateReq> consignmentOrderLineRequests = convertConsignmentOrderLineUpdateReq(mnSapIf033Request.getGoodsInfos(), mnSapIf033Request.getFactoryCode(), mnSapIf033Request.getWareHouseCode());
        consignmentOrderUpdateRequest.setConsignmentOrderLineRequest(consignmentOrderLineRequests);
        return consignmentOrderUpdateRequest;

    }

    private ConsignmentOrderWriteCreateRequest convertConsignmentOrderWriteCreateRequest(MnSapIf033Request mnSapIf033Request) {
        ConsignmentOrderWriteCreateRequest consignmentOrderWriteCreateRequest = new ConsignmentOrderWriteCreateRequest();
        consignmentOrderWriteCreateRequest.setOuterDeliveryOrderId(mnSapIf033Request.getDeliverOrderNo());
        consignmentOrderWriteCreateRequest.setPickingStatus(mnSapIf033Request.getPickingStatus());
        //todo bz,sap 交货单明细回传会返回过账状态，但这个时间应该还没有过账，是否不用保存？待与pd确认
//        consignmentOrderWriteCreateRequest.set(mnSapIf033SDO.getBillStatus());
        consignmentOrderWriteCreateRequest.setDeliverType(mnSapIf033Request.getDeliverType());
        //todo bz,与pd确认sap返回的orderNo是否是sap的销售单号
        consignmentOrderWriteCreateRequest.setOuterSalesOrderId(mnSapIf033Request.getOrderNo());
        consignmentOrderWriteCreateRequest.setOuterStoOrderId(mnSapIf033Request.getOrderNo());
        //todo bz,凭证日期怎么传
//        consignmentOrderWriteCreateRequest.set(mnSapIf033SDO.getProofDate());
//        consignmentOrderWriteCreateRequest.set(mnSapIf033SDO.getFactoryCode());
        //todo bz,工厂编码及库存地点
//        consignmentOrderWriteCreateRequest.set(mnSapIf033SDO.getWareHouseCode());
        consignmentOrderWriteCreateRequest.setTransportSite(mnSapIf033Request.getTransportSite());
        consignmentOrderWriteCreateRequest.setTransportRouteCode(mnSapIf033Request.getTransportRouteCode());
        consignmentOrderWriteCreateRequest.setTransportRouteDesc(mnSapIf033Request.getTransportRouteDesc());
        consignmentOrderWriteCreateRequest.setNetWeight(mnSapIf033Request.getNetWeight());
        consignmentOrderWriteCreateRequest.setGrossWeight(mnSapIf033Request.getGrossWeight());
        consignmentOrderWriteCreateRequest.setVolume(mnSapIf033Request.getVolume());
        consignmentOrderWriteCreateRequest.setWeightUnit(mnSapIf033Request.getWeightUnit());
        consignmentOrderWriteCreateRequest.setVolumeUnit(mnSapIf033Request.getVolumeUnit());
        consignmentOrderWriteCreateRequest.setTransportRequire(mnSapIf033Request.getTransportRequire());
        consignmentOrderWriteCreateRequest.setSendToCode(mnSapIf033Request.getSendtoCode());
        consignmentOrderWriteCreateRequest.setSoldToCode(mnSapIf033Request.getSoldToCode());
        consignmentOrderWriteCreateRequest.setSalesOrgId(mnSapIf033Request.getSaleOrg());
        consignmentOrderWriteCreateRequest.setDistributeChannel(mnSapIf033Request.getDistributeChannel());
        consignmentOrderWriteCreateRequest.setDepartment(mnSapIf033Request.getDepartment());
        consignmentOrderWriteCreateRequest.setDeliverPriority(mnSapIf033Request.getDeliverPriority());
        consignmentOrderWriteCreateRequest.setDeliverPlanDate(mnSapIf033Request.getDeliverPlanDate());
        consignmentOrderWriteCreateRequest.setSendPlanDate(mnSapIf033Request.getSendPlanDate());
        consignmentOrderWriteCreateRequest.setRemark(mnSapIf033Request.getRemark());
        consignmentOrderWriteCreateRequest.setCreator(mnSapIf033Request.getCreateCode());
        consignmentOrderWriteCreateRequest.setCreatDate(TimeUtil.parseSimpleDateFormat(mnSapIf033Request.getCreateDate()));
        consignmentOrderWriteCreateRequest.setModifier(mnSapIf033Request.getUpdateCode());
        consignmentOrderWriteCreateRequest.setModifidDate(TimeUtil.parseSimpleDateFormat(mnSapIf033Request.getUpdateDate()));
        List<ConsignmentOrderLineRequest> consignmentOrderLineRequests = convertConsignmentOrderLineRequest(mnSapIf033Request.getGoodsInfos(), mnSapIf033Request.getFactoryCode(), mnSapIf033Request.getWareHouseCode());
        consignmentOrderWriteCreateRequest.setConsignmentOrderLineRequest(consignmentOrderLineRequests);
        return consignmentOrderWriteCreateRequest;
    }

    private List<ConsignmentOrderLineRequest> convertConsignmentOrderLineRequest(List<MnSapIf033Detail> mnSapIf033Details, String factoryCode, String inventoryCode) {

        List<ConsignmentOrderLineRequest > consignmentOrderLineRequests = mnSapIf033Details.stream().map(mnSapIf033Detail -> {
            ConsignmentOrderLineRequest consignmentOrderLineRequest = new ConsignmentOrderLineRequest();
            consignmentOrderLineRequest.setOuterOrderLineId(mnSapIf033Detail.getProjectNo());
            //todo bz,与pd确认 getMateriaCode对应是否正确
            consignmentOrderLineRequest.setScItemId(mnSapIf033Detail.getMateriaCode());
            consignmentOrderLineRequest.setSapBatchNo(mnSapIf033Detail.getSapBatchNo());
            consignmentOrderLineRequest.setQty(StringUtils.trim(mnSapIf033Detail.getDeliverNum()));
            consignmentOrderLineRequest.setBaseUnit(mnSapIf033Detail.getBaseUnit());
            consignmentOrderLineRequest.setSaleUnit(mnSapIf033Detail.getSaleUnit());
            consignmentOrderLineRequest.setNetWeight(StringUtils.trim(mnSapIf033Detail.getNetWeightGoods()));
            consignmentOrderLineRequest.setGrossWeight(StringUtils.trim(mnSapIf033Detail.getGrossWeightGoods()));
            consignmentOrderLineRequest.setVolumeGoods(StringUtils.trim(mnSapIf033Detail.getVolumeGoods()));
            consignmentOrderLineRequest.setAskProductionDate(mnSapIf033Detail.getAskProductionDate());
            consignmentOrderLineRequest.setActProductionDate(mnSapIf033Detail.getActProductionDate());
            //todo bz
            consignmentOrderLineRequest.setFactoryCode(factoryCode);
            consignmentOrderLineRequest.setInventoryCode(inventoryCode);
            return consignmentOrderLineRequest;
        }).collect(Collectors.toList());
        return consignmentOrderLineRequests;
    }

    private List<ConsignmentOrderLineUpdateReq> convertConsignmentOrderLineUpdateReq(List<MnSapIf033Detail> mnSapIf033Details, String factoryCode, String inventoryCode) {
        List<ConsignmentOrderLineUpdateReq> consignmentOrderLineRequests = mnSapIf033Details.stream().map(mnSapIf033Detail ->{
            ConsignmentOrderLineUpdateReq consignmentOrderLineUpdateReq = new ConsignmentOrderLineUpdateReq();
            consignmentOrderLineUpdateReq.setOuterOrderLineId(mnSapIf033Detail.getProjectNo());
            //todo bz,与pd确认 getMateriaCode对应是否正确
            consignmentOrderLineUpdateReq.setScItemId(mnSapIf033Detail.getMateriaCode());
            consignmentOrderLineUpdateReq.setSapBatchNo(mnSapIf033Detail.getSapBatchNo());
            consignmentOrderLineUpdateReq.setQty(StringUtils.trim(mnSapIf033Detail.getDeliverNum()));
            consignmentOrderLineUpdateReq.setBaseUnit(mnSapIf033Detail.getBaseUnit());
            consignmentOrderLineUpdateReq.setSaleUnit(mnSapIf033Detail.getSaleUnit());
            consignmentOrderLineUpdateReq.setNetWeight(StringUtils.trim(mnSapIf033Detail.getNetWeightGoods()));
            consignmentOrderLineUpdateReq.setGrossWeight(StringUtils.trim(mnSapIf033Detail.getGrossWeightGoods()));
            consignmentOrderLineUpdateReq.setVolumeGoods(StringUtils.trim(mnSapIf033Detail.getVolumeGoods()));
            consignmentOrderLineUpdateReq.setAskProductionDate(mnSapIf033Detail.getAskProductionDate());
            consignmentOrderLineUpdateReq.setActProductionDate(mnSapIf033Detail.getActProductionDate());
            //todo bz
            consignmentOrderLineUpdateReq.setFactoryCode(factoryCode);
            consignmentOrderLineUpdateReq.setInventoryCode(inventoryCode);
            return consignmentOrderLineUpdateReq;
        }).collect(Collectors.toList());
        return consignmentOrderLineRequests;
    }

    /**
     * 请求009
     * 中台交货单明细回传OTW
     */
    private Result<Void> bcLink009Request(MnSapIf033Request mnSapIf033Request ){
        ConsignmentOrderQueryRequest consignmentOrderQueryRequest = new ConsignmentOrderQueryRequest();
        consignmentOrderQueryRequest.setOuterDeliveryOrderId(mnSapIf033Request.getDeliverOrderNo());
        log.info("mnSapIf009 searchOrder consignmentOrder param:{}", JSON.toJSONString(consignmentOrderQueryRequest));
        Result<ConsignmentOrderSearchResponse> queryConsignmentOrderResult = consignmentOrderQueryService.searchOrder(consignmentOrderQueryRequest);
        log.info("mnSapIf009 searchOrder consignmentOrder result:{}", JSON.toJSONString(queryConsignmentOrderResult));
        if (queryConsignmentOrderResult.isSuccess()) {
            ConsignmentOrderSearchResponse orderSearchResponse = queryConsignmentOrderResult.getResult();
            Map<String, String> header = HttpTokenUtil.generateHttpHeader();
            String urlPrefix = OtsApplicationAdapterSdkConstants.urlPrefix();
            String url = urlPrefix + "api/mn_bc_link/inOutBoundOrderDetailSyncOtw";
            DeliveryOrderSapDTORequest dtoRequest = new DeliveryOrderSapDTORequest();
            //交货单号
            dtoRequest.setOuterDeliverOrderNo(RemoveZeroUtil.removeZeroPrefix(orderSearchResponse.getOuterDeliveryOrderId()));
            //总体积
            dtoRequest.setVolume(orderSearchResponse.getVolume());
            //总重量
            dtoRequest.setGrossWeight(orderSearchResponse.getGrossWeight());
            List<DeliveryOrderSapDetailDTORequest> param = new ArrayList<>();
            orderSearchResponse.getConsignmentOrderLine().forEach(orderLineSearchResponse ->{
                DeliveryOrderSapDetailDTORequest orderSapDetailDTORequest = new DeliveryOrderSapDetailDTORequest();
                //交货单行号
                orderSapDetailDTORequest.setOuterDeliverOrderLineNo(orderLineSearchResponse.getOuterOrderLineId());
                //毛重
                orderSapDetailDTORequest.setGrossWeight(orderLineSearchResponse.getGrossWeight());
                //交货数量
                orderSapDetailDTORequest.setQuantity(orderLineSearchResponse.getQty());
                //体积
                orderSapDetailDTORequest.setVolumeGoods(orderLineSearchResponse.getVolumeGoods());
                param.add(orderSapDetailDTORequest);
            });
            dtoRequest.setDetailList(param);
            log.info("009  call bc link interface,url:{}, header:{}, param:{}", url, header, JSON.toJSONString(dtoRequest));
            ResponseEntity<com.alibaba.cirtus.ots.application.adapter.ability.model.Result> post = httpUtils.post(url, header, dtoRequest, com.alibaba.cirtus.ots.application.adapter.ability.model.Result.class);
            com.alibaba.cirtus.ots.application.adapter.ability.model.Result result = post.getBody();
            log.info("009 inOutBoundOrderCreate mnOtwCommonResponse result:{}", JSON.toJSONString(result));
            if (!result.isSuccess()) {
                return Result.fail(result.getErrorCode(),result.getMessage());
            }
        }
        return Result.success(null);
    }
    //根据销售单查询出入库单号（是否要判断销售货调拨）
    private Result<WarehousingOrderDTO> queryInOutboundBySaleOrderId(String salesOrderBizNo){
        QueryWmsOrderByOtherOrderRequest queryWmsOrderByOtherOrderRequest = new QueryWmsOrderByOtherOrderRequest();
        queryWmsOrderByOtherOrderRequest.setBizOrderId(salesOrderBizNo);
        queryWmsOrderByOtherOrderRequest.setContainSubOrders(true);
        log.info("017 queryInOutBoundByDelivery request:{}", JSON.toJSONString(queryWmsOrderByOtherOrderRequest));
        Result<WarehousingOrderDTOResponse> result = otsApplicationAdapterSdkService.queryWmsOrderByOtherOrder(queryWmsOrderByOtherOrderRequest);
        log.info("017 queryInOutBoundByDelivery response:{}", JSON.toJSONString(result));
        if(result.isSuccess() && CollectionUtils.isNotEmpty(result.getResult().getWarehousingOrders())){
            List<WarehousingOrderDTO> warehousingOrderDTOList = result.getResult().getWarehousingOrders().stream().filter(warehousingOrderDTO ->
                 warehousingOrderDTO.getMainOrderType().equals(WmsOrderMainTypeEnum.SALES_OUT.getValue())
            ).collect(Collectors.toList());
             return Result.success(warehousingOrderDTOList.get(0));
        }
        return Result.fail(result.getErrorCode(),"根据订单查询出入库单失败或为空:" +result.getMessage());
    }
}
